﻿using System.Linq;
using System.Reflection;
using Ef.Core.Imp.Entity;
using Microsoft.EntityFrameworkCore;

namespace Ef.Core.Imp
{
    /// <summary>
    /// 自定义 数据上下文
    /// </summary>
    public class DynamicDbContext2 : DbContext
    {
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            MappingEntityTypes(modelBuilder);
            base.OnModelCreating(modelBuilder);
        }

        private void MappingEntityTypes(ModelBuilder modelBuilder)
        {
            var assembly = Assembly.GetExecutingAssembly();
            var types = assembly?.GetTypes();
            var list = types?.Where(t =>
                    t.IsClass && !t.IsGenericType && !t.IsAbstract &&
                    t.GetInterfaces().Any(m =>
                        m.IsAssignableFrom(typeof(EntityBase)))).ToList();
            if (list.Any())
            {
                list.ForEach(t =>
                  {
                      if (modelBuilder.Model.FindEntityType(t) == null)
                          modelBuilder.Model.AddEntityType(t);
                  });
            }
        }
    }
}
